<template>
  <customContainer ref="customContainerRef" :config="config" />
  <div class="cash-label-container">
    <el-descriptions>
      <el-descriptions-item label="应收金额">{{amount}}</el-descriptions-item>
      <el-descriptions-item label="已收金额">{{paidAmount}}</el-descriptions-item>
      <el-descriptions-item label="未收金额">{{uncollectedAmount}}</el-descriptions-item>
    </el-descriptions>
  </div>
  <customContainer ref="customContainerRef" :config="config1" />
  <orderDetailDialog ref="orderDetailVueRef" />
</template>

<script setup lang="ts" name="AirSeaExpressDetail">
import { ref, getCurrentInstance, reactive, computed, defineAsyncComponent } from 'vue'
import { useRoute } from 'vue-router'
import { ElButton, ElMessageBox, ElMessage } from 'element-plus'
import { getSeaAirSendFinanceAccountDetail, singleEliminate,collectionList } from '@/api/finance/receiverManange'
import { detailTableItem, detailExportParams } from '../receiveabeTypes'
import { DictDirection } from '@/store/modules/dicts'
import { getSummaries,depClone } from '@/utils'

const orderDetailDialog = defineAsyncComponent(() => import('./components/OrderDetailDialog.vue'))
const {
  appContext: {
    config: {
      globalProperties: { $download },
    },
  },
} = getCurrentInstance()
const route = useRoute()

const multipleSelection = ref<detailTableItem[]>([])
const queryParams = reactive<object>({
  pageSize: 10,
  pageNum: 1,
  marketProducts: undefined,
  waybillNo: undefined,
  timeRange: undefined,
  endTime: undefined,
  beginTime: undefined,
  serialNo: route.params.serialNo,
})
const eportLoading = ref<boolean>(false)
const orderDetailVueRef = ref(null)
const customContainerRef = ref(null)
const config = computed({
  get() {
    return {
      query: {
        fields: [
          // {
          //   type: 'select',
          //   label: '客户名称',
          //   prop: 'customerCode',
          //   option: {
          //     dictInfo: { dict: DictDirection.客户 },
          //   },
          // },
          {
            label: '客户单号',
            prop: 'waybillNo',
          },
          {
            type: 'select',
            label: '销售产品',
            prop: 'marketProducts',
            option:{
              clearable:true,
              dictInfo: { dict: DictDirection.销售产品 },
            }
          },
          {
            type: 'date-picker',
            label: '下单时间',
            prop: 'timeRange',
            option: {
              startPlaceholder: "开始时间",
              endPlaceholder: "结束时间",
              type: 'daterange',
            },
          },
        ],
        queryParams,
        formOption: {},
      },
      btns: [
        {
          title: '导出',
          type: 'primary', 
          loading: eportLoading.value,
          onClick(e) {
            // 默认传账单号，勾选传ids[]
            const data:detailExportParams = {}
            if (multipleSelection.value.length) {
              data.ids = multipleSelection.value.map(i => i.id)
            } else {
              data.serialNo = route.query.serialNo as string
            }
            eportLoading.value = true
            $download(
              'finance/seaAirSendFinanceAccount/listExport', 
              data, 
              `空海派、快递账单_${ new Date().getTime() }.xlsx`,
            )
            .finally(() => {
              eportLoading.value = false
            })
          },
        },
      ],
      table: {
        columns: [
          { type: 'selection', width: '55' },
          { label: '下单时间', align: 'center', prop: 'createDate' },
          { label: '客户名称', align: 'center', prop: 'customerName' },
          { label: '单价', align: 'center', prop: 'unitPrice' },
          { label: '总实重', align: 'center', prop: 'receivingTotalWeight' },
          { label: '总材积重', align: 'center', prop: 'receivingTotalWood' },
          { label: '总计费重', align: 'center', prop: 'receivingTotalCharging' },
          { label: '总件数', align: 'center', prop: 'receivingTotal' },
          { label: '单报总金额', align: 'center', prop: 'singleReportAmount' },
          { label: '附加费', align: 'center', prop: 'surcharge' },
          { label: '应收总金额', align: 'center', prop: 'amount' },
          { label: '客户单号', align: 'center', prop: 'waybillNo' },
          { label: '订单号', align: 'center', prop: 'orderNo' },
          { label: '销售产品', align: 'center', prop: 'marketProducts' },
          { label: '国家', align: 'center', prop: 'consigneeCountry' },
          { label: '收货站点',
            align: 'center',
            prop: 'site',
            autoFormatter: {
              dict: DictDirection.收货站点,
              rowKey: 'site',
            } },
          { label: '邮编', align: 'center', prop: 'consigneePostcode' },
          { label: '是否报关件',
            align: 'center',
            prop: 'customsDeclaration',
            formatter(row) {
              return row.customsDeclaration == '1' ? '是' : '否'
            } },
          { label: '备注', align: 'center', prop: 'remarks' },
          {
            label: '操作',
            align: 'center',
            width: '200',
            fixed: 'right',
            render(h, params) {
              return [
                h(
                  ElButton,
                  {
                    text: true,
                    type: 'primary',
                    onClick: () => {
                      orderDetailVueRef.value.open(params.row)
                    },
                  },
                  {
                    default: () => '订单详情',
                  },
                ),
                h(
                  ElButton,
                  {
                    text: true,
                    type: 'primary',
                    onClick: () => {
                      ElMessageBox.confirm('是否单票剔除？', '提示', {
                        confirmButtonText: '确定',
                        cancelButtonText: '取消',
                      }).then(() => {
                        singleEliminate({
                          orderNo: params.row.orderNo,
                        }).then(res => {
                          if (res.code === 200) {
                            ElMessage.success('操作成功！')
                            customContainerRef.value.getList()
                          }
                        })
                      })
                    },
                  },
                  {
                    default: () => '单票剔除',
                  },
                ),
              ]
            },
          },
        ],
        event: {
          onSelectionChange: (rows) => {
            multipleSelection.value = rows
          },
          showSummary: true,
          summaryMethod: getSummaries([
            { column: 'unitPrice' },
            { column: 'receivingTotalWeight' },
            { column: 'receivingTotalWood' },
            { column: 'receivingTotalCharging' },
            { column: 'receivingTotal' },
            { column: 'singleReportAmount' },
            { column: 'surcharge' },
            { column: 'amount' },
            { column: 'amount' },
          ]),
        },
      },
      api: (data) => {
        const params = depClone(data)

        if(params.waybillNo)
          params.waybillNo = params.waybillNo.replaceAll(/\s+/g, ',')

        if(params.timeRange && Array.isArray(params.timeRange) ){
          params.beginTime = params.timeRange[0]
          params.endTime = params.timeRange[1]
          delete params.timeRange
        }
        return getSeaAirSendFinanceAccountDetail(params)
      },
    }
  },
  set(val) {
    return val
  },
})



const {amount,paidAmount,uncollectedAmount} = route.query

// const multipleSelection = ref<detailTableItem[]>([])
const queryParams1 = reactive<object>({
  pageSize: 10,
  pageNum: 1,
  serialNo: route.params.serialNo,
})
// const eportLoading = ref<boolean>(false)
// const orderDetailVueRef = ref(null)
// const customContainerRef = ref(null)
const config1 = computed({
  get() {
    return {
      query: {
        fields: [],
        queryParams:queryParams1,
        formOption: {},
      },
      btns: [],
      table: {
        columns: [
          { label: '账单号', align: 'center', prop: 'serialNo' },
          { label: '收款时间', align: 'center', prop: 'receivingDate' },
          { label: '收款金额', align: 'center', prop: 'paymentAmount' },
          { label: '收款人', align: 'center', prop: 'receivingUser' },
          { label: '收款账号', align: 'center', prop: 'receivingAccount' },
          { label: '是否开票', align: 'center', prop: 'isBilling' ,
           formatter(row){
              return ['否', '是'][row.isBilling]
           }},
          { label: '开票时间', align: 'center', prop: 'invoiceDate' },
          { label: '开票金额', align: 'center', prop: 'totalAmount' },
        ],
        event: {
          showSummary: true,
          summaryMethod: getSummaries([{ column: 'paymentAmount' },{ column: 'totalAmount' }]),
        },
      },
      api: collectionList,
    }
  },
  set(val) {
    return val
  },
})

</script>
<style lang="less" scoped>
.cash-label-container{
   padding:16px 16px 0 ;
   margin-bottom: -16px;
   /deep/.el-descriptions__body{
   border-radius: 8px;
    .el-descriptions__cell{
      padding-top:12px;
      padding-left:12px;
    }
   }
}
</style>